package compile_and_download

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"test/unit_function/flash_device"
)

type Rk3568ImgFromInternet struct {
	Rk3568Img
}

type response struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Data    data   `json:"data"`
}

type data struct {
	Rate  string  `json:"rate"`
	Count int     `json:"count"`
	List  subList `json:"list"`
}

type subList struct {
	CurrentPage int             `json:"currentPage"`
	DataList    []dailyBuildVos `json:"dataList"`
}

type result struct {
	DailyBuildVos []dailyBuildVos `json:"dailyBuildVos"`
}

type dailyBuildVos struct {
	ImgObsPath string `json:"imgObsPath"`
}

// Compile 编译任务：上传脚本，执行脚本，下载产物
func (receiver *Rk3568ImgFromInternet) Compile() error {
	return nil
}

func GetLatestLink() string {
	url := "http://ci.openharmony.cn/api/daily_build/build/list/component"
	method := "POST"
	// type=0 是每日构建 type=1 是滚动构建
	payload := strings.NewReader(`{
	"pageNum": 1,
	"pageSize": 8,
	"branch": "master",
	"component": "dayu200",
	"projectName": "openharmony",
    "type": 0
	}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return ""
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	var tmp response
	err = json.Unmarshal(body, &tmp)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	vos := tmp.Data.List.DataList
	for _, vo := range vos {
		if vo.ImgObsPath != "" {
			return vo.ImgObsPath
		}
	}
	return ""
}

func DownloadFileFromInternet(reciever *Rk3568ImgFromInternet) {

	// 1.请求获取最新的已经编译成功的镜像包
	link := GetLatestLink()
	reciever.ImgLink = link
	log.Println("current link is", link)
	// 2.下载镜像包，并到"D:/auto_test/img"路径下，重命名为image.tar.gz
	DownloadFile(link, "image.tar.gz", "D:/auto_test/img")

}

func DownloadFile(url, localFile, dir string) {
	original, err := os.Getwd()
	if err != nil {
		log.Println(err)
	} else {
		defer os.Chdir(original)
	}
	err = os.Chdir(dir)
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	println("resp size=", resp.ContentLength)
	defer resp.Body.Close()

	// 创建一个文件用于保存
	out, err := os.Create(localFile)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	// 然后将响应流和文件流对接起来
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		panic(err)
	}
}

func (receiver *Rk3568ImgFromInternet) Download() error {
	// TODO 下载文件并解压
	DownloadFileFromInternet(receiver)
	cmd := exec.Command("tar", "-zxvf", "image.tar.gz")
	cmd.Dir = "D:/auto_test/img"
	err := cmd.Run()
	if err != nil {
		log.Println("error occurred when executing tar -zxvf image.tar.gz ", err)
		return err
	}
	log.Println("executing tar -zxvf image.tar.gz succeed")
	log.Println("downloading img succeed!")
	return nil
}

func (receiver *Rk3568ImgFromInternet) Execute() error {
	flash_device.FlashDevice("D:/DeployDevice/resource/RK3568_tool/upgrade_tool.exe", "D:/auto_test/img")
	return nil
}
